#!/bin/bash

# 设置颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 获取项目根目录
PROJECT_ROOT=$(cd "$(dirname "$0")/../.." && pwd)
FRONTEND_DIR="$PROJECT_ROOT/mcphub-frontend-vue3"
BACKEND_DIR="$PROJECT_ROOT/mcphub-backend-django"
DOCS_DIR="$PROJECT_ROOT/mcphub-docs-vitepress"
DEPLOY_DIR="$PROJECT_ROOT/mcphub-scripts/deploy"
LOGS_DIR="$DEPLOY_DIR/logs"

echo -e "${GREEN}==== MCPRepoMarket 一键启动脚本 ====${NC}"
echo -e "${YELLOW}项目根目录: $PROJECT_ROOT${NC}"

# 确保日志目录存在
mkdir -p "$LOGS_DIR"

# 停止可能正在运行的服务
echo -e "\n${GREEN}停止现有服务...${NC}"
pkill -f "gunicorn"
echo -e "${GREEN}服务已停止${NC}"

# 启动Django后端
echo -e "\n${GREEN}启动后端服务...${NC}"
cd "$BACKEND_DIR" || exit 1
source venv/bin/activate
nohup gunicorn mcphub.wsgi:application --bind 127.0.0.1:8000 --workers 4 > "$LOGS_DIR/backend.log" 2>&1 &
echo $! > "$DEPLOY_DIR/backend.pid"
echo -e "${GREEN}后端服务已启动在端口 8000${NC}"

# 检查Nginx是否正在运行
echo -e "\n${GREEN}检查并启动Nginx...${NC}"
if ! systemctl is-active --quiet nginx; then
    sudo systemctl start nginx
fi
echo -e "${GREEN}Nginx已启动${NC}"

echo -e "\n${GREEN}所有服务已启动！${NC}"
echo -e "您可以通过访问 http://mcp.clouddragon.huawei.com 来访问MCPRepoMarket"
echo -e "查看日志: tail -f $LOGS_DIR/backend.log"
echo -e "停止服务: ./stop.sh" 